package com.webblog.controller;

import com.webblog.pojo.Blog;
import com.webblog.pojo.BlogMapClassify;
import com.webblog.pojo.BlogMapTags;
import com.webblog.service.blogMapClassify.BlogMapClassifyService;
import com.webblog.service.blog.BlogService;
import com.webblog.service.blogMapTags.BlogMapTagService;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;


@CrossOrigin
@Controller
@RequestMapping("/blog")
public class BlogController {

    private Logger logger = Logger.getLogger(BlogController.class);

    @Autowired
    private BlogService blogService;

    @Autowired
    private BlogMapClassifyService blogMapClassifyService;

    @Autowired
    private BlogMapTagService blogMapTagService;

    /**
     * 上传图片并返回给前端回显
     * @param file 上传的图片资源
     * @param request
     * @return
     */
    @RequestMapping(value="/upload/img",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadimg(@RequestParam("image") MultipartFile file, HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String, Object>();
        if(!file.isEmpty())
        {
            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().substring(0,5);
            StringBuffer buffer = new StringBuffer(fileName);
            buffer.insert(fileName.lastIndexOf("."),uuid);
            fileName = buffer.toString();
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd/");
            String stringDate = format.format(date);
            fileName = stringDate + fileName;
            String path = request.getSession().getServletContext().getRealPath("blog_images");
            File targetFile = new File(path,fileName);
            String projectPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/blog_images";
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            try {
                if(file.getInputStream().available()>0){
                    file.transferTo(targetFile);
                }
                resultMap.put("success","true");
                resultMap.put("msg","上传图片成功");
                resultMap.put("path","/blog_images/"+fileName);
                resultMap.put("url",projectPath+"/"+fileName);
            }
            catch (Exception e){
                resultMap.put("success","false");
                resultMap.put("msg","上传图片失败");
                e.printStackTrace();
            }
        }
        return resultMap;
    }

    @RequestMapping(value = "/upload/cover",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadcover(@RequestParam("blogimg") MultipartFile file, HttpServletRequest request){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        if(!file.isEmpty()){
            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().substring(0,5);
            fileName = new  StringBuffer(fileName).insert(fileName.lastIndexOf("."),uuid).toString();
            String path = request.getSession().getServletContext().getRealPath("blog_cover");
            File targetFile = new File(path,fileName);
            String projectPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/blog_cover";
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            try {
                if(file.getInputStream().available()>0){
                    file.transferTo(targetFile);
                }
                System.out.println();
                resultMap.put("success","true");
                resultMap.put("msg","上传Blog封面成功");
                resultMap.put("path","/blog_cover/"+fileName);
                resultMap.put("url",projectPath+"/"+fileName);
            }
            catch (Exception e){
                e.printStackTrace();
                resultMap.put("success","false");
                resultMap.put("msg","上传Blog封面失败");
            }
        }
        return resultMap;
    }

    @RequestMapping(value = "/remove/img",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> removeCover(@RequestParam("imgPath") String imgPath,HttpServletRequest request){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        String imgForder = "";
        String fileName = "";
        if (imgPath.startsWith("/blog_cover")){
            imgForder = "blog_cover";
            fileName = imgPath.substring(11);
        }
        if (imgPath.startsWith("/blog_images")){
            imgForder = "blog_images";
            fileName = imgPath.substring(12);
        }
        String path = request.getSession().getServletContext().getRealPath(imgForder);
        File file = new File(path+fileName);
        if(file.exists()){
            file.delete();
            resultMap.put("success",true);
            resultMap.put("msg","文件移除成功");
        }
        else {
            resultMap.put("success",false);
            resultMap.put("msg","文件移除失败");
        }
        return resultMap;
    }


    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> addBlog(Blog blog,@RequestParam("classifyId")int classifyId,@RequestParam("tags")Integer[] tagArray){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        blog.setCreationDate(new Date());
        blog.setModifyDate(new Date());
        int blogId = blogService.addnewBlog(blog);
        ArrayList tagList = new ArrayList();
        for (Integer i : tagArray) {
            tagList.add(new BlogMapTags(i,blogId));
        }
        blogMapTagService.addTagList(tagList);
        if(blogId>0){
            blogMapClassifyService.add(new BlogMapClassify(classifyId,blogId));
            resultMap.put("success",true);
            resultMap.put("msg","保存成功");
        }
        else{
            resultMap.put("success",false);
            resultMap.put("msg","保存失败");
        }
        return resultMap;
    }

    /**
     *
     * @param isDraft 0为已发布，1为在草稿箱
     * @return
     */
    @RequestMapping(value = "/blogList/{isDraft}",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getBlogList(@PathVariable int isDraft){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        List<Blog> blogList = new ArrayList<Blog>();
        blogList = blogService.getBlogList(isDraft);
        if(blogList.size()>0){
            resultMap.put("success",true);
            resultMap.put("blogList",blogList);
            resultMap.put("msg","获取数据成功");
        }
        else{
            resultMap.put("success",false);
            resultMap.put("blogList",blogList);
            resultMap.put("msg","暂无数据");
        }
        return resultMap;
    }

    @RequestMapping(value = "/{blogId}",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getBlogDetail(@PathVariable int blogId){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        Blog blog = blogService.getBlogDetail(blogId);
        if(blog != null){
            resultMap.put("success",true);
            resultMap.put("blog",blog);
        }
        else {
            resultMap.put("success",false);
            resultMap.put("blog",null);
        }
        return resultMap;
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateBlog(Blog blog,@RequestParam("classifyId")int classifyId,@RequestParam("tags")Integer[] tagArray){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        blog.setModifyDate(new Date());
        ArrayList tagList = new ArrayList();
        for (Integer i : tagArray) {
            tagList.add(new BlogMapTags(i,blog.getBlogId()));
        }
        blogMapTagService.updateTagList(tagList,blog.getBlogId());
        if(blogService.updateBlog(blog)>0){
            blogMapClassifyService.update(new BlogMapClassify(classifyId,blog.getBlogId()));
            resultMap.put("success",true);
            resultMap.put("msg","修改成功");
        }
        else {
            resultMap.put("success",false);
            resultMap.put("msg","修改失败");
        }
        return resultMap;
    }


    @RequestMapping(value = "/recoveryList",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getRecoverList(){
        int isRecovery = 1;
        Map<String,Object> resultMap = new HashMap<String, Object>();
        List<Blog> blogList = new ArrayList();
        blogList = blogService.getCoveryList(isRecovery);
        if(blogList.size()>0){
            resultMap.put("success",true);
            resultMap.put("blogList",blogList);
            resultMap.put("msg","获取数据成功");
        }
        else{
            resultMap.put("success",false);
            resultMap.put("blogList",blogList);
            resultMap.put("msg","暂无数据");
        }
        return resultMap;
    }


    @RequestMapping(value = "/toRecovery/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> updateBlogToRecover(@PathVariable int id){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        if(blogService.setRecovery(id)>0){
            resultMap.put("success",true);
            resultMap.put("msg","已放入回收站");
        }
        else {
            resultMap.put("success",false);
            resultMap.put("msg","放入回收站失败");
        }
        return resultMap;
    }

    @RequestMapping(value = "/recovery/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> recoveryBlog(@PathVariable int id){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        if(blogService.recoveryBlog(id)>0){
            resultMap.put("success",true);
            resultMap.put("msg","恢复成功");
        }
        else {
            resultMap.put("success",false);
            resultMap.put("msg","恢复失败");
        }
        return resultMap;
    }

    @RequestMapping(value = "/remove/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> removeBlog(@PathVariable int id){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        if(blogService.deleteBlog(id)>0){
            blogMapClassifyService.removeMapper(id);
            blogMapTagService.removeTagList(id);
            resultMap.put("success",true);
            resultMap.put("msg","删除成功");
        }
        else {
            resultMap.put("success",false);
            resultMap.put("msg","删除失败");
        }
        return resultMap;
    }

    @RequestMapping(value = "/publish/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> publishBlog(@PathVariable int id){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        if(blogService.publishBlog(id)>0){
            resultMap.put("success",true);
            resultMap.put("msg","发布成功");
        }
        else {
            resultMap.put("success",false);
            resultMap.put("msg","发布失败");
        }
        return resultMap;
    }

    @RequestMapping(value = "/search",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> searchBlog(@RequestParam("title")String title){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        List blogList = blogService.searchBlog(title);
        if(blogList!=null){
            resultMap.put("success",true);
            resultMap.put("msg","查找成功");
            resultMap.put("data",blogList);
        }
        else{
            resultMap.put("success",false);
            resultMap.put("msg","查找失败");
        }
        return resultMap;
    }

    @RequestMapping(value = "/getRecent",method = RequestMethod.GET)
    @ResponseBody
    public List<Blog> getRecent(){
        List<Blog> blogList = blogService.getRecentBlog();
        return blogList;
    }

    @RequestMapping(value = "/classify/{id}",method = RequestMethod.GET)
    @ResponseBody
    public List<Blog> getBlogByClassify(@PathVariable int id){
        List<Blog> blogList = blogService.getBlogByClassifyId(id);
        return blogList;
    }

    @RequestMapping(value = "/updateReadCount/{id}",method = RequestMethod.GET)
    @ResponseBody
    public boolean updateReadCount(@PathVariable int id){
        if(blogService.updateReadCount(id)>0){
            return true;
        }
        return false;
    }
}
